import { defineStore } from 'pinia';
import { loginApi } from '@/api/auth';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
  }),
  actions: {
    setToken(token) {
      this.token = token;
      localStorage.setItem('token', token);
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    logout() {
      this.token = '';
      this.userInfo = {};
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    },
    async login(username, password) {
      try {
        const res = await loginApi({ username, password });
        if (res.code === 200) {
          this.setToken(res.data.token);
          this.setUserInfo(res.data.user);
          return true;
        }
        return false;
      } catch (error) {
        throw error;
      }
    }
  }
});